// 地址路由
const express = require("express");
// 引入connect-multiparty中间件
var multipart = require("connect-multiparty");
// 创建中间件对象
var multipartMiddleware = multipart();
// 引入数据库配置
const db = require("../mysql");
// 创建路由对象
const address = express.Router();
// 根据昵称获取地址信息
address.get('/getAddress/:username', multipartMiddleware, (req, res) => {
    const sqlStr = `select * from address where address_username = '${req.params.username}'`
    db.query(sqlStr, (err, results) => {
        if (err) return res.json({ code: 400, message: '获取地址失败' });
        res.json({ code: 200, data: results });
    });
})

// 根据收货人真实名称获取地址信息
address.get('/getAddressByName/:consignee', multipartMiddleware, (req, res) => {
    const sqlStr = `select * from address where consignee = '${req.params.consignee}'`
    db.query(sqlStr, (err, results) => {
        if (err) return res.json({ code: 400, message: '获取地址失败' });
        res.json({ code: 200, data: results });
    });
})

// 增加地址
address.post('/addAddress', multipartMiddleware, (req, res) => {
    const sqlStr = `insert into address (address_username,consignee,address_phone,postcode,province,address)  values ('${req.body.username}','${req.body.consignee}','${req.body.address_phone}','${req.body.postcode}','${req.body.province}','${req.body.address}')`
    db.query(sqlStr, (err, results) => {
        if (err) return res.json({ code: 400, message: '设置地址失败' });
        return res.json({ code: 200, message: '设置地址成功' })
    })
})
// 修改地址
address.put('/updateAddress', multipartMiddleware, (req, res) => {
    const sqlStr = `update address set consignee='${req.body.consignee}',address_phone='${req.body.address_phone}',postcode='${req.body.postcode}',province='${req.body.province}',	address='${req.body.address}' where address_username='${req.body.username}'`
    db.query(sqlStr, (err, results) => {
        if (err) return res.json({ code: 400, message: '修改地址失败' });
        return res.json({ code: 200, message: '修改地址成功' })
    })
})
module.exports = address
